package proxy_pattern.remote.ex2;

import proxy_pattern.remote.ex2.to.Request;

import java.nio.charset.StandardCharsets;
import java.rmi.RemoteException;
import java.util.Base64;

/**
 * @author 申书航
 * @version 1.0
 *
 * MyBase64类实现了IBase64接口，用于对Request对象进行Base64编码和解码。
 */
public class MyBase64 implements IBase64 {
    @Override
    /**
     * 将Request对象进行编码，返回Base64字符串。
     * @param request 要编码的Request对象
     * @return 编码后的Base64字符串
     * @throws RemoteException 远程调用异常
     */
    public String encode(Request request) throws RemoteException {
        String tmp = request.getId() + ":" + request.getId();
        return Base64.getEncoder().encodeToString(tmp.getBytes(StandardCharsets.UTF_8));
    }

    @Override
    /**
     * 将Base64字符串解码为Request对象。
     * @param encodeStr 编码的Base64字符串
     * @return 解码后的Request对象
     * @throws RemoteException 远程调用异常
     */
    public Request decode(String encodeStr) throws RemoteException {
        String tmp = new String(Base64.getDecoder().decode(encodeStr),StandardCharsets.UTF_8);
        String[] split = tmp.split(":");
        Request request = new Request();
        request.setId(Integer.valueOf(split[0]));
        request.setMessage(split[1]);
        return request;
    }
}
